#include "bookmark.h"

void print_bookmark_array(json_t *bookmark_array)
{
    static size_t depth = 0;
    json_t *item;
    char *type, *name;
    for (size_t i = 0; i < json_array_size(bookmark_array); i++) {
        item = json_array_get(bookmark_array, i);
        type = (char *) json_string_value(json_object_get(item, "type"));
        name = (char *) json_string_value(json_object_get(item, "name"));

        if (strcmp(type, "url") == 0) {
            indent(depth, 4);
            printf("%s\n", name);
        }
        else {
            indent(depth, 4);
            printf("%s:\n", name);
            depth++;
            print_bookmark_array(json_object_get(item, "children"));
            depth--;
            indent(depth, 4);
            printf("%s end\n", name);
        }
    }
}

size_t get_index(json_t *folder, const char *name)
{
    json_t *item_name;

    for (size_t i = 0; i < json_array_size(folder); i++) {
        item_name = json_object_get(
                        json_array_get(folder, i),
                    "name");
        if (strcmp(json_string_value(item_name), name) == 0) {
            return i;
        }
    }
    return -1;
}

json_t *get_folder(json_t *root, char **path, size_t depth)
{
#ifdef DEBUG
    putchar('\n');
    printf("Get: \n");
    print_2d_char_array(stdout, path, depth);
#endif
    json_t *folder;
    folder = json_object_get(
                json_object_get(root, path[0]),
             "children");
    for (size_t i = 1; i < depth; i++) {
        folder = json_array_get(folder, get_index(folder, path[i]));
        folder = json_object_get(folder, "children");
    }
    return folder;
}

void move(json_t *src_list, size_t src_index, json_t *dest_list)
{
    json_array_append(dest_list, json_array_get(src_list, src_index));
    json_array_remove(src_list, src_index);
}
